import TencentCloudChat from '@tencentcloud/chat';
import { TUIChatKit } from '../pages/TUIKit';
import { TUILogin } from '@tencentcloud/tui-core';
import { playList } from '@/utils/beep.ts'
import { getUserImInfo } from '@/utils/api/userInfo.ts'
import { ref } from 'vue'

TUIChatKit.init();
const chat = ref(TencentCloudChat.create({ SDKAppID: 1600043419 }))
chat.value.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, function (event) {
	// 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
	// event.name - TencentCloudChat.EVENT.MESSAGE_RECEIVED
	// event.data - 存储 Message 对象的数组 - [Message]
	console.log("收到IM消息....", event)
	playList(["dididi"])
})
chat.value.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, function (event) {
	console.log(event)
	notReadCount.value = event.data
	if (event.data > 0) {
		uni.showTabBarRedDot({
			index: 2
		})
	} else {
		uni.hideTabBarRedDot({
			index: 2
		})
	}
});
export const notReadCount = ref(0)
export const connectIm = async () => {
const { userID } = TUILogin.getContext();
	const userRes = await getUserImInfo()
	if (userID && userID == userRes.data.imUserId) {
		return
	}
	if (userID && userID != userRes.data.imUserId) {
		TUILogin.logout();
	}
	await TUILogin.login({
		SDKAppID: 1600043419,
		userID: userRes.data.imUserId,
		userSig: userRes.data.imUserSign,
		useUploadPlugin: true,
		framework: `vue3`
	})
	let totalUnreadCount = chat.value.getTotalUnreadMessageCount();
	if (totalUnreadCount > 0) {
		uni.showTabBarRedDot({
			index: 2
		})
	} else {
		uni.hideTabBarRedDot({
			index: 2
		})
	}
	notReadCount.value = totalUnreadCount
	console.log('总未读数量', totalUnreadCount)
	// #ifdef APP-PLUS
	
	// #endif

}


export const logoutIm = () => {

	const { userID } = TUILogin.getContext();
	if (userID) {
		TUILogin.logout();
	}


}